package com.cm.projectx.common;

import com.cm.projectx.common.entity.UserContext;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

/**
 * 创建拦截器处理请求头信息
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws UnsupportedEncodingException {

        // 从请求头获取用户ID
        String userId = request.getHeader("userId");
        String userName = request.getHeader("userName");
        String idCardName = request.getHeader("idCardName");
        String orgRoute = request.getHeader("orgRoute");
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(userId)) {
             //设置到上下文
            UserContext.UserInfo userInfo = new UserContext.UserInfo();
            userInfo.setUserId(userId);
            if (StringUtils.isNotBlank(idCardName)) {
                userInfo.setIdCardName(URLDecoder.decode(idCardName, StandardCharsets.UTF_8.toString()));
            }
            if (StringUtils.isNotBlank(orgRoute)) {
                userInfo.setOrgRoute(URLDecoder.decode(orgRoute, StandardCharsets.UTF_8.toString()));
            }
            if (StringUtils.isNotBlank(userName)) {
                userInfo.setUserName(URLDecoder.decode(userName, StandardCharsets.UTF_8.toString()));
            }
            userInfo.setToken(token);
            UserContext.setCurrentUser(userInfo);
        } else {
            // 如果没有用户ID，可以抛出异常或进行其他处理
            throw new RuntimeException("用户ID不能为空");
        }
        return true;
    }
    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) {
        // 请求完成后清理线程局部变量，防止内存泄漏
        UserContext.clear();
    }
}
